﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace WoWConnecter
{
    internal class AccountData
    {
        public string Account { get; set; }
        public string Password { get; set; }

    }

    public class BaseClient
    {
        protected TcpClient mClient;
        protected NetworkStream mStream;
        protected byte[] mBuffer;

        public string Username { get; internal set; }
        public string HashPassword { get; internal set; }
        public string Password { get; internal set; }
        protected SecureRemotePassword SecurePassword { get; set; }
        protected PacketHandler PacketHandler { get; set; }

        public const int BufferSize = 1024;

        public BaseClient(string username, string password)
        {
            Username = username.ToUpper();
            Password = password.ToUpper();
            HashPassword = ASCIIEncoding.ASCII.GetString(SecureRemotePassword.GenerateCredentialsHash(Username, Password.ToUpper()));
        }

        public virtual void Connect(string realmlist)
        {
            var ip = Dns.GetHostAddresses(realmlist);

            if (ip.Length > 0)
            {
                mClient = new TcpClient();
                mClient.Connect(ip, 3724);
                mStream = new NetworkStream(mClient.Client);
                mBuffer = new byte[BufferSize];
                BeginReceive();
            }
        }

        protected virtual void BeginReceive()
        {
            mStream.BeginRead(mBuffer, 0, mBuffer.Length, OnReceive, null);
        }

        protected virtual void OnReceive(IAsyncResult result)
        {

        }

        public virtual void Disconnect()
        {
            Console.WriteLine();
        }

        public virtual void Send(BasicPacketOut packet)
        {
            byte[] output = packet.Finalize();

            mStream.Write(output, 0, output.Length);
            mStream.Flush();
        }

        public virtual void HandlePacket(BasicPacketIn packet)
        {
            PacketHandler.Handle(packet);
        }
    }
}
